//
//  LDBaseWebViewController.swift
//  DingDongZP
//
//  Created by 三秒文化 on 16/5/18.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

import UIKit
import NJKWebViewProgress
import JavaScriptCore

class LDBaseWebViewController: LDBaseCustomizeVC {

    var webview:UIWebView?
    var reqUrl = String()
    
    var progressView:NJKWebViewProgressView?
    var progressProxy:NJKWebViewProgress?
    var preIsShowTabbarStatus = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationController?.interactivePopGestureRecognizer?.delegate = self
        
        webview = UIWebView()
//        webview!.translatesAutoresizingMaskIntoConstraints = true
        
        progressProxy = NJKWebViewProgress()
        progressView = NJKWebViewProgressView(frame: CGRectMake(0, 43, view.width, 1))

        
        webview?.delegate = progressProxy
        progressProxy?.webViewProxyDelegate = self
        progressProxy?.progressDelegate = self
        
        navigationController?.navigationBar.addSubview(progressView!)
        navigationController?.navigationBar.bringSubviewToFront(progressView!)
        view.addSubview(webview!)
        
        let url = NSURL.init(string: reqUrl)
        let request = NSURLRequest.init(URL: url!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 5)
        
        webview?.loadRequest(request)
        
//        let cangoback = webview?.canGoBack
//        
//        RACObserve(self, "cangoback").subscribeNext { (obj) in
//            
//            print(obj)
//        }
        
      
    }
    

    
    deinit {
        
        progressView?.removeFromSuperview()
        webview?.removeFromSuperview()
    }
    
    override func viewWillAppear(animated: Bool) {
        
        navigationController?.navigationBar.setBackgroundImage(UIImage.setImageWithColor(LDGolbalColor.Green), forBarMetrics: UIBarMetrics.Default)
        navigationController?.navigationBar.shadowImage = UIImage.setImageWithColor(UIColor.clearColor())
        
        rdv_tabBarController.setTabBarHidden(true, animated: false)
//        webview?.frame = view.frame;
//        webview?.translatesAutoresizingMaskIntoConstraints = false
        
        webview?.snp_makeConstraints(closure: { (make) in
            
            make.top.equalTo(0)
            make.left.right.equalTo(0)
            make.bottom.equalTo(view.snp_bottom)
        })
        
        
        let recognizer = UISwipeGestureRecognizer.init(target: self, action: #selector(self.gotoBack))
        recognizer.direction = UISwipeGestureRecognizerDirection.Right
        self.webview?.addGestureRecognizer(recognizer)
//        [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
//        [[self view] addGestureRecognizer:recognizer];
        
        view.layoutIfNeeded()
        
    }
    
    func gotoBack() {
        
    }
    
    override func viewWillDisappear(animated: Bool) {
              
//        rdv_tabBarController.setTabBarHidden(false, animated: false)
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:LDFont.Font16,NSForegroundColorAttributeName:LDFontColor.White]
        LDShowHUB.shareInstance.dissmiss()
    }
}

extension LDBaseWebViewController:UIGestureRecognizerDelegate {
    
    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
        
        return false
    }

}

extension LDBaseWebViewController:UIWebViewDelegate,NJKWebViewProgressDelegate{
    
    func webViewProgress(webViewProgress: NJKWebViewProgress!, updateProgress progress: Float) {
//        print(progress)
        progressView?.setProgress(progress, animated: true)
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let url = request.URL
        let strUrl = NSString.init(string: url?.absoluteString ?? "")
        
        if strUrl.containsString("dev") {
            
            let range = strUrl.rangeOfString("dev")
            let subStr = strUrl.substringFromIndex(range.location)
            
            if subStr.containsString("menu_id=hrservice") {
                
                let vc = feedBackVC()
                vc.titleArr = ["系统消息","客服","常见问题"]
                navigationController?.pushViewController(vc, animated: false)
            }
            
            return false
        }
        
        return true
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        self.title = "加载中..."
//        LDShowHUB.shareInstance.showToastStatus("加载中...")
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        LDShowHUB.shareInstance.dissmiss()
        
        let current = webview?.stringByEvaluatingJavaScriptFromString("document.title")
        title = current
        self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:LDFont.Font15,NSForegroundColorAttributeName:LDFontColor.White]
        
//        //注入js
//        let context = webView.valueForKey("documentView.webView.mainFrame.javaScriptContext") as? JSContext ?? JSContext()
//        let jsStr = "alert('test....')"
//        
//        context?.evaluateScript(jsStr)
        
        //读取
        
//        let context = webView.valueForKey("documentView.webView.mainFrame.javaScriptContext") as? JSContext ?? JSContext()
//        
//        let call1:()->() = {
//            
//            print("js-call")
//        }
//        
//        context?.setObject(unsafeBitCast(call1, AnyObject.self), forKeyedSubscript: "test")
        
    }
}